﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using Combres;
using NetWing.Common.SMS;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Data.SqlServer;
using NetWing.BPM.Core.Bll;
using NetWing.BPM.Core.Model;
using NetWing.BPM.Core.Dal;
using Senparc.CO2NET;
using Senparc.Weixin;
using Senparc.CO2NET.RegisterServices;
using Senparc.Weixin.Entities;

namespace NetWing.BPM.Admin
{
    public class Global : System.Web.HttpApplication
    {

        public static string appName = NetWing.Common.ConfigHelper.GetValue("systemName");//定义系统名称
        public static string copyRight = NetWing.Common.ConfigHelper.GetValue("copyRight");
        public static string mainUrl = NetWing.Common.ConfigHelper.GetValue("website");//设置主站连接

        protected void Application_Start(object sender, EventArgs e)
        {
            //在 global.asax.cs 文件的 Application_Start() 方法中，加入代码（注意 using 两个命名空间：Senparc.CO2NET 和 Senparc.Weixin）：
            var isGLobalDebug = true;//设置全局 Debug 状态
            var senparcSetting = SenparcSetting.BuildFromWebConfig(isGLobalDebug);
            var register = RegisterService.Start(senparcSetting).UseSenparcGlobal();//CO2NET全局注册，必须！

            var isWeixinDebug = true;//设置微信 Debug 状态
            var senparcWeixinSetting = SenparcWeixinSetting.BuildFromWebConfig(isWeixinDebug);
            register.UseSenparcWeixin(senparcWeixinSetting, senparcSetting);////微信全局注册，必须！



            RouteTable.Routes.AddCombresRoute("Combres");
            //设置自动发短信定时器
            System.Timers.Timer timer = new System.Timers.Timer(1000 * 60 * 60*3);//1000等于1秒 //3个小时来一次
            timer.Elapsed += new System.Timers.ElapsedEventHandler(AutoSMS);
            timer.Interval = 1000*60*60*3;//3个小时检查一次
            timer.AutoReset = true;
            timer.Enabled = true;
        }

        /// <summary>
        /// 自动发提醒短信
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AutoSMS(object sender, EventArgs e)
        {

            //模版CODE:
            //SMS_119075627
            //模版内容:
            //${user}您好：我是${ depname}，您的${ room}将于${ expdate}到期，请您尽快来商务中心办理相关手续。电话:${ tel}.

            Application.Lock();

            LogModel logx = new LogModel();
            logx.BusinessName = "自动发催费短信任务已执行";
            logx.OperationIp = "127.0.0.1";
            logx.OperationTime = DateTime.Now;
            logx.PrimaryKey = "";
            logx.UserId = 9;
            logx.SqlText = "";
            logx.TableName = "";
            logx.note = "执行时间是:"+DateTime.Now.ToString();
            logx.OperationType = (int)OperationType.Sys;
            LogDal.Instance.Insert(logx);

            //先列出所有房间 找出5天内过期，或者已过期的
            //2018-1-8 是过期时间  2018-1-3 是系统当前时间  
            //select DATEDIFF(day, '2018-1-8', '2018-1-3')=-5
            //以上值为-5表明还有5天到期。如果是5表明是已过期5天



            System.Data.DataTable rdt = NetWing.Common.Data.SqlServer.SqlEasy.ExecuteDataTable("select * from MJRooms where exp_time is not null  and exp_time='2011-11-11' and  (DATEDIFF(dd, exp_time, GETDATE()) >= -5) and  ((DATEDIFF(dd, smsdate, GETDATE())<>0) or smsdate is null)");
            foreach (System.Data.DataRow dr in rdt.Rows)
            {
                //得到部门手机号
                DataRow mdr = SqlEasy.ExecuteDataRow("select * from Sys_Departments where keyid="+dr["depid"]+"");
                string tels = "13700615775,13700605160,"+mdr["tel"].ToString()+"";
                string templateno = "SMS_119075627";
                string smsparam = "{\"user\":\""+dr["usernames"].ToString()+ "\",\"depname\":\"Me+国际青年公寓(" + mdr["DepartmentName"].ToString() + ")\",\"room\":\"房间:" + dr["roomnumber"].ToString()+ "\",\"expdate\":\"" + dr["exp_time"].ToString() + "\",\"tel\":\"" + mdr["tel"].ToString() + "\"}";
                aliyunsms sms =  new aliyunsms();
                string r = sms.send(tels,templateno,smsparam);
                if (r=="OK")
                {
                    LogModel log = new LogModel();
                    log.BusinessName = "发送催费短信成功";
                    log.OperationIp = "127.0.0.1";
                    log.OperationTime = DateTime.Now;
                    log.PrimaryKey = "";
                    log.UserId = 9;
                    log.TableName = "";
                    log.SqlText = "select * from MJRooms where exp_time is not null and  (DATEDIFF(dd, exp_time, GETDATE()) > -5) and  ((DATEDIFF(dd, smsdate, GETDATE())<>0) or smsdate is null)";
                    log.note = "发送结果:" + r + "手机号：" + tels + "短信参数：" + smsparam + "短信模板编号：" + templateno;
                    log.OperationType = (int)OperationType.Sys;
                    LogDal.Instance.Insert(log);
                    //发送成功，写发送结果到数据库
                    SqlEasy.ExecuteNonQuery("update MJRooms set smsdate='" + DateTime.Now.ToString() + "' where keyid=" + dr["keyid"].ToString() + " ");//更新短信发送时间

                }
                else
                {
                    LogModel log = new LogModel();
                    log.BusinessName = "发送催费短信失败";
                    log.OperationIp = "127.0.0.1";
                    log.OperationTime = DateTime.Now;
                    log.PrimaryKey = "";
                    log.UserId = 9;
                    log.SqlText = "select * from MJRooms where exp_time is not null and  (DATEDIFF(dd, exp_time, GETDATE()) > -5) and  ((DATEDIFF(dd, smsdate, GETDATE())<>0) or smsdate is null)";
                    log.TableName = "";
                    log.note = "发送结果:" + r + "手机号：" + tels+"短信参数："+smsparam+"短信模板编号："+templateno;
                    log.OperationType = (int)OperationType.Sys;
                    LogDal.Instance.Insert(log);
                }
  


            }


            //这里可以写你需要执行的任务，比如说，清理数据库的无效数据或增加每个用户的积分等等
            Application.UnLock();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}